import 'package:flutter/cupertino.dart';
import 'package:flutter_blog_manage_study/base/get/get_extension.dart';
import 'package:flutter_blog_manage_study/model/request_result.dart';
import 'package:flutter_blog_manage_study/util/toast_util.dart';
import 'package:get/get.dart';

import 'http_request.dart';

/// * 作者: Tao
/// * 日期: 2024/3/20
/// * 时间: 15:47
/// * 描述: 上层请求封装
///
/// 使用方法
///
/// Request.get("/login",{"userName": 'admin', "pwd": '123456'} ,success: (data) {
///
/// } , fail: (code , msg){
///
/// });
///
class Request {
  /// 发起GET请求
  /// * [url] 请求url
  /// * [parameters] 请求参数
  /// * [isJson] 是否是json提交 默认 true
  /// * [dialog] 是否显示加载框 默认 true
  /// * [success] 请求成功回调
  /// * [fail] 请求失败回调
  static void get<T>(
    String url,
    parameters, {
    bool isJson = true,
    bool dialog = true,
    Success<T>? success,
    Fail? fail,
  }) {
    _request(Method.GET, url, parameters,
        isJson: isJson, dialog: dialog, success: success, fail: fail);
  }

  /// 发起POST请求
  /// * [url] 请求url
  /// * [parameters] 请求参数
  /// * [isJson] 是否是json提交 默认 true
  /// * [dialog] 是否显示加载框 默认 true
  /// * [success] 请求成功回调
  /// * [fail] 请求失败回调
  static void post<T>(
    String url,
    parameters, {
    bool isJson = true,
    bool dialog = true,
    Success<T>? success,
    Fail? fail,
  }) {
    _request(Method.POST, url, parameters,
        isJson: isJson, dialog: dialog, success: success, fail: fail);
  }

  /// 发起请求
  static void _request<T>(
    Method method,
    String url,
    parameters, {
    bool isJson = false,
    bool dialog = true,
    Success<T>? success,
    Fail? fail,
  }) {
    if (dialog) {
      Get.showLoading();
    }

    /// 检验参数中是否携带URL，如果携带，则替换
    parameters.foreach((key, value) {
      if (url.contains(key)) {
        url = url.replaceAll('{$key}', value.toString());
      }
    });

    HttpRequest.request(method, url, parameters, isJson: isJson,
        success: (data) {
      if (dialog) {
        Get.dismiss();
      }
      if (success != null) {
        var result = RequestResult.fromJson(data);
        debugPrint("request result ==============> $result");
        if (result.errorCode == 0) {
          success(result.data);
        } else {
          /// 其他状态
          ToastUtil.show(result.errorMsg);
        }
      }
    }, fail: (code, msg) {
      if (dialog) {
        Get.dismiss();
      }
      ToastUtil.show(msg);
      fail?.call(code, msg);
    });
  }
}
